import 'package:flutter/material.dart';
import 'package:secend_flutter/bean/search_model_bean.dart';
import 'package:secend_flutter/bottom_bar/speak_page.dart';
import 'package:secend_flutter/dao/search_dao.dart';
import 'package:secend_flutter/dao/tao_ean.dart';
import 'package:secend_flutter/define_widget/appbar_search_widget.dart';
import 'package:secend_flutter/define_widget/webview_widget.dart';

const TYPES = [
  'channelgroup',
  'gs',
  'plane',
  'train',
  'cruise',
  'district',
  'food',
  'hotel',
  'huodong',
  'shop',
  'sight',
  'ticket',
  'travelgroup'
];
const URL =
    'https://m.ctrip.com/restapi/h5api/globalsearch/search?source=mobileweb&action=mobileweb&keyword=';

class SearchPage extends StatefulWidget {
  final bool? hideLeft;
  final String searchUrl;
  final String? keyword;
  final String? hint;

  const SearchPage(
      {Key? key, this.hideLeft, this.searchUrl = URL, this.keyword, this.hint})
      : super(key: key);

  @override
  _SearchPageState createState() => _SearchPageState();
}

class _SearchPageState extends State<SearchPage> {
  SearchModel? searchModel;
  String? keyword;

  @override
  void initState() {
    if(widget.keyword!=null){
      _textChange(widget.keyword!);
    }
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Column(
      children: [
        Container(
            decoration: const BoxDecoration(
              gradient: LinearGradient(
                  colors: [Color(0x66000000), Colors.transparent],
                  end: Alignment.topCenter,
                  begin: Alignment.bottomCenter),
            ),
            child: Container(
              padding: const EdgeInsets.only(top: 30),
              height: 80,
              decoration: const BoxDecoration(color: Colors.white),
              child: AppBarSearch(
                hideLeftS: widget.hideLeft,
                hintS: widget.hint,
                defaultTextS: widget.keyword,
                searchBarTypeS: SearchBarTypeS.normal,
                inputBoxClick: () {},
                speakOnClick: _speakClick,
                leftButtonOnClick: _leftClick,
                onTextChanged: _textChange,
                rightButtonOnClick: _rightClick,
              ),
            )),
        MediaQuery.removePadding(
            context: context,
            removeTop: true,
            child: Expanded(
                flex: 1,
                child: ListView.builder(
                    itemCount: searchModel?.data?.length ?? 0,
                    itemBuilder: (context, index) {
                      return _item(index);
                    })))
      ],
    ));
  }

  _speakClick() {
    Navigator.push(
        context, MaterialPageRoute(builder: (context) => const SpeakPage()));
  }

  _leftClick() {
    Navigator.pop(context);
  }

  void _textChange(String value) {
    keyword = value;
    if (value.length == 0) {
      setState(() {
        searchModel = null;
      });
      return;
    }
    String url = widget.searchUrl + value;
    searchData(url, value).then((SearchModel model) {
      if (model.keyWord == keyword) {
        setState(() {
          //当当前输入内容与服务器返回一致才会渲染
          searchModel = model;
        });
      }
    }).catchError((e) {
      print(e);
    });
  }

  void _rightClick() {}

  Widget _item(int index) {
    if (searchModel == null || searchModel!.data == null) {
      return const Text('无值');
    }
    SearchItem searchItem = searchModel!.data![index]!;
    return GestureDetector(
      onTap: () {
        Tiaboon.push(
            context,
            MyWebView(
              url: searchItem.url,
              title: '详情',
            ));
      },
      child: Container(
        padding: const EdgeInsets.all(10),
        decoration: const BoxDecoration(
            border: Border(bottom: BorderSide(width: 0.3, color: Colors.grey))),
        child: Row(
          children: [
            Container(
              margin: const EdgeInsets.all(2),
              child: Image.asset(
                _typeImage(searchItem.type!),
                width: 26,
                height: 26,
              ),
            ),
            Column(
              children: [
                Container(
                  width: 280,
                  child: _title(searchItem),
                ),
                Container(
                    width: 280,
                    margin: const EdgeInsets.only(top: 10),
                    child: _subtitle(searchItem)),
              ],
            )
          ],
        ),
      ),
    );
  }

  _typeImage(String type) {
    if (type == null) return 'images/type_travelgroup.png';
    String path = 'travelgroup';
    for (var value in TYPES) {
      if (type.contains(value)) {
        path = value;
        break;
      }
    }
    return 'images/type_$path.png';
  }

  _title(SearchItem searchItem) {
    if (searchItem == null) return null;
    List<TextSpan> spans = [];
    spans.addAll(_kewordTextSpans(searchItem.word!, searchModel!.keyWord!));
    spans.add(TextSpan(
        text: ' ' +
            (searchItem.districtname ?? '') +
            ' ' +
            (searchItem.zonename ?? ""),
        style: const TextStyle(color: Colors.grey, fontSize: 17)));
    return RichText(text: TextSpan(children: spans));
  }

  _subtitle(SearchItem searchItem) {
    return RichText(
        text: TextSpan(children: <TextSpan>[
      TextSpan(
          text: searchItem.price ?? '',
          style: const TextStyle(color: Colors.orange, fontSize: 16)),
      TextSpan(
          text: " " + (searchItem.sourceType ?? ''),
          style: const TextStyle(color: Colors.grey, fontSize: 12)),
    ]));
  }

  Iterable<TextSpan> _kewordTextSpans(String word, String keyWord) {
    List<TextSpan> spans = [];
    if (word == null || word.length == 0) return spans;
    List<String> arr = word.split(keyWord);
    TextStyle normalStyle =
        const TextStyle(color: Colors.black87, fontSize: 16);
    TextStyle keyWordStyle =
        const TextStyle(color: Colors.orange, fontSize: 16);
    for (int i = 0; i < arr.length; i++) {
      String val = arr[i];
      // if (i % 2 == 1) {
      //   spans.add(TextSpan(text: keyWord, style: keyWordStyle));
      // }

      // if (val != null && val.length > 0) {
      //   spans.add(TextSpan(text: val, style: normalStyle));
      // }
      if(val.isEmpty){
        spans.add(TextSpan(text: keyWord,style: keyWordStyle));
      }else{
        spans.add(TextSpan(text: val,style: normalStyle));
        if(i!=arr.length-1){
          spans.add(TextSpan(text: keyWord,style: keyWordStyle));
        }
      }
    }
    // for (String value in arr) {
    //   print(value);
    //   if(value!=''){
    //     spans.add(TextSpan(text: keyWord,style: keyWordStyle));
    //   }else{
    //     spans.add(TextSpan(text: value,style: normalStyle));
    //   }
    // }
    return spans;
  }
}
